import typing

from fastapi import APIRouter
from pydantic import BaseModel

from DataModels.database import Asset
from DataModels.share import RespInfo, RespResultCode, StatusInfo

from utils.asset import asset_to_info

update_router = APIRouter(prefix="/update")


class UpdateRequest(BaseModel):
    id: str
    name: typing.Optional[str] = None
    remark: typing.Optional[str] = None
    width: typing.Optional[int] = None
    height: typing.Optional[int] = None


@update_router.post("")
async def update_asset(data: UpdateRequest) -> RespInfo:
    """
    更新 Asset 对象时， （对象） `id` 为必填项。

    |字段|说明|
    | --- | --- |
    |id| str|
    |name| Optional[str] = None|
    |remark| Optional[str] = None|
    |width| Optional[int] = None|
    |height| Optional[int] = None|

    """
    oid = data.id
    asset = await Asset.find_one(Asset.id == oid)
    if not asset:
        return RespInfo(
            status=StatusInfo(
                code=RespResultCode.AssetNotFound,
                msg="资产不存在",
            )
        )

    if data.name:
        asset.name = data.name
    if data.remark:
        asset.remark = data.remark
    if data.width:
        asset.width = data.width
    if data.height:
        asset.height = data.height
    await asset.save()  # type: ignore

    return RespInfo(
        status=StatusInfo(
            code=RespResultCode.Success,
            msg="更新成功",
        ),
        info=asset_to_info(asset),
    )
